package com.haizhi.workstation.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 操作.JSON文件的工具类
 */
@Slf4j
public class JSONUtil {
    /**
     * 保存.JSON文件
     * @param pathname 文件名
     * @param data  文件内容
     */
    public static void saveDataToFile(String pathname,String data) {
        BufferedWriter writer = null;
        File file = new File( pathname + ".json");
        //如果文件不存在，则新建一个
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //写入
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8"));
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("文件写入成功：====={}",pathname);
    }

    /**
     * 读取.JSON文件
     * @param file 文件
     * @return 文件内容
     */
    public static String getDataFromFile(File file) {

        String Path=file.getAbsolutePath();
        BufferedReader reader = null;
        String lastStr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(Path);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                lastStr += tempString;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return lastStr;
    }
}
